package ran.quzitech.rnutils;

import android.content.Context;
import android.os.Environment;
import android.os.SystemClock;
import android.telecom.Call;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by ran on 2017/08/16.
 */
public class UtilManager extends ReactContextBaseJavaModule /*implements ActivityEventListener */ {
    private Context context;
    private ReactContext reactContext;
    private static final String TAG = "UtilManager";
    private Callback configCallback;
    private EspWifiAdminSimple mWifiAdmin;

    private UDPSocketServer mSocketServer;
    private volatile boolean mIsInterrupt = false;

    @Override
    public String getName() {
        return "UtilManager";
    }

    public UtilManager(ReactApplicationContext reactContext) {
        super(reactContext);
        context = reactContext;
        this.reactContext = reactContext;
        mWifiAdmin = new EspWifiAdminSimple(context);
        //  initHandler();
    }

    private void initUdpServerSocket(int port, int timeout) {
        Log.v(TAG, "==============initUdpServerSocket===============");
        stopUdpServer();
        mSocketServer = new UDPSocketServer(port,
                timeout, context);
        mIsInterrupt = false;

    }

    @ReactMethod
    public void getWifiConnectedSsid(Callback callback) {
        if (mWifiAdmin.getWifiConnectedSsid() == null) {
            callback.invoke("");
        } else {
            callback.invoke(null, mWifiAdmin.getWifiConnectedSsid());
        }


    }

    @ReactMethod
    public void performClick(final int x, final int y, Callback callback) {

        getCurrentActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.v(TAG, x + "" + y);
                View view = getCurrentActivity().getWindow().getDecorView();


                MotionEvent evenDownt = MotionEvent.obtain(System.currentTimeMillis(),
                        System.currentTimeMillis(), MotionEvent.ACTION_DOWN, x, y, 0);
                view.dispatchTouchEvent(evenDownt);
                MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(),
                        System.currentTimeMillis() + 50, MotionEvent.ACTION_UP, x, y, 0);
                view.dispatchTouchEvent(eventUp);
                evenDownt.recycle();
                eventUp.recycle();
            }
        });

    }


    @ReactMethod
    private void receiveSpecLenByte(final int port, final int timeout, final int expectDataLen, final Callback callback) {


        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.v(TAG, "==============receiveSpecLenByte===============");
                initUdpServerSocket(port, timeout);
                byte[] receiveBytes = null;
                Log.v(TAG, "接收进入阻塞");

                receiveBytes = mSocketServer
                        .receiveSpecLenBytes(expectDataLen);

                if (receiveBytes != null) {
                    String dd = convertHexToString(ByteUtil.byte2hex(receiveBytes).replace(" ", ""));
                    callback.invoke(null, dd);
                } else {
                    callback.invoke("fail");
                }

                stopUdpServer();
            }
        }).start();


    }

    /**
     * 根据byte数组生成文件
     *
     * @param
     */
    @ReactMethod
    private void createFileWithByte(String hexStr, String fileName, Callback callback) {
        // TODO Auto-generated method stub
        /**
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */
        File file = new File(fileName);
        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 如果文件存在则删除
            if (file.exists()) {
                file.delete();
            }
            // 在文件系统中根据路径创建一个新的空文件
            file.createNewFile();
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(HexString.hexToBytes(hexStr));
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();

            callback.invoke(null, fileName);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            callback.invoke(e);
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }


    public String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }
        return sb.toString();
    }

    private synchronized void stopUdpServer() {

        Log.v(TAG, "==============stopUdpServer===============");
        if (!mIsInterrupt) {
            mIsInterrupt = true;
            Log.v(TAG, "stop udp server");
            if (mSocketServer != null) {
                mSocketServer.interrupt();
            }

        }
    }
}


